package com.candy.candyshortlink.business.controller;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.candy.candycommon.utils.BeanConvertUtils;
import com.candy.candycommon.utils.ResultBean;
import com.candy.candyshortlink.business.entity.ShortLink;
import com.candy.candyshortlink.business.service.IShortLinkService;
import com.candy.candyshortlink.utils.Request;
import com.candy.candyshortlink.utils.RequestMerge;
import com.candy.candyshortlinkservice.dto.ShortLinkDTO;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.web.bind.annotation.*;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author suyanlong
 * @since 2022-10-25
 */
@Slf4j
@RestController
@RequestMapping("/shortLink")
@AllArgsConstructor
public class ShortLinkController implements InitializingBean {

    private final IShortLinkService iLogLinkService;

    @PostMapping("convert")
    public ResultBean convert(@RequestBody ShortLinkDTO shortLinkDTO) {
        log.info("保存日志" + JSONObject.toJSONString(shortLinkDTO));
        ShortLink shortLink = BeanConvertUtils.convertTo(shortLinkDTO, ShortLink::new);
        iLogLinkService.createShortLink(shortLink);
        shortLinkDTO.setShortUrl(shortLink.getShortUrl());
        return ResultBean.ok(shortLinkDTO);
    }

    @PostMapping("convertBatch")
    public ResultBean convertBatch(@RequestBody List<ShortLinkDTO> shortLinkDTOList) {
        log.info("保存日志" + JSONObject.toJSONString(shortLinkDTOList));
        List<ShortLink> shortLinkList = BeanConvertUtils.convertListTo(shortLinkDTOList, ShortLink::new);
        List<ShortLinkDTO> result = BeanConvertUtils.convertListTo(iLogLinkService.createShortLinkBatch(shortLinkList), ShortLinkDTO::new);
        return ResultBean.ok(result);
    }

    @GetMapping("getById")
    public ResultBean getById(@RequestParam Long id) throws Exception {
        Request request = new Request();
        request.setId(id);
        CompletableFuture<ShortLink> future = new CompletableFuture<>();
        request.setFuture(future);
        RequestMerge.request.add(request);
//        return ResultBean.ok(iLogLinkService.getById(id)); // 单条查询
        return ResultBean.ok(request.getFuture().get());
    }

    @PostConstruct
    public void handle() {
        ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1);
        scheduledExecutorService.scheduleAtFixedRate(() -> {
//            log.info("----------------------");
            int size = RequestMerge.request.size();
            if (size == 0)
                return;

            List<Request> requests = new ArrayList<>(size);
            for (int i = 0; i < size; i++) {
                Request request = (Request) RequestMerge.request.poll();
                requests.add(request);
            }
            System.out.println("批量处理了" + size + "条请求");

            List<Long> codes = new ArrayList<>();
            for (Request request : requests) {
                codes.add(request.getId());
            }

            QueryWrapper<ShortLink> shortLinkQueryWrapper = new QueryWrapper<>();
            shortLinkQueryWrapper.in("id", codes);
            List<ShortLink> shortLinkList = iLogLinkService.list(shortLinkQueryWrapper);

            Map<Long, ShortLink> mapResult = new HashMap<>();
            for (ShortLink shortLink : shortLinkList) {
                mapResult.put(shortLink.getId(), shortLink);
            }

            //返回请求
            for (Request request : requests) {
                ShortLink shortLink = mapResult.get(request.getId());
                request.getFuture().complete(shortLink);
            }
        }, 0, 10, TimeUnit.MILLISECONDS);
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        ShortLinkDTO shortLinkDTO = new ShortLinkDTO();
        shortLinkDTO.setChannel("ds");
        shortLinkDTO.setSourceUrl("https://pc-zatest1.zhongan.com/open/common/downloadFileScreen/downloadDoc.json?data=c240e162db60103bcc26c06b04ad7abe6cef6a528061789efe626c65a1e3a430");
        ResultBean save = convert(shortLinkDTO);
        log.info(JSONObject.toJSONString(save));
        save = convert(shortLinkDTO);
        log.info(JSONObject.toJSONString(save));
        save = convert(shortLinkDTO);
        log.info(JSONObject.toJSONString(save));
        save = convert(shortLinkDTO);
        log.info(JSONObject.toJSONString(save));
    }

}
